import { defineStore } from "pinia";
import { UserLoginVo } from "@/model/LoginModel.ts";
import { ref, Ref } from "vue";
import router from "@/router/router.ts";

export const useLocalStore = defineStore("local", () => {

    //用户信息Vo字符串
    const userInfoVoStr: Ref<string> = ref("");
    //用户信息Vo对象
    const userInfoVo: Ref<UserLoginVo> = ref({});

    /**
     * 将用户信息Json转为obj并存储到localStorage
     * @param userInfoVoStr 用户信息Json
     */
    const setUserInfoVoJson = (userInfoVoStr: string) => {
        userInfoVo.value = JSON.parse(userInfoVoStr);
        localStorage.setItem("UserInfoVo", userInfoVoStr);
    };


    /**
     * 将用户信息obj存储到localStorage
     * @param userInfoVo 用户信息Json
     */
    const setUserInfoVo = (userInfoVo: UserLoginVo) => {
        userInfoVo.value = userInfoVoStr;
        localStorage.setItem("UserInfoVo", JSON.stringify(userInfoVo));
    };

    /**
     * 获取用户信息Vo对象
     */
    const getUserInfoVo = () => {
        if (userInfoVo.value) {
            return userInfoVo.value;
        } else {
            let userInfoVoStr: string = localStorage.getItem("UserInfoVo");
            if (userInfoVoStr) {
                userInfoVo.value = JSON.parse(userInfoVoStr);
                return userInfoVo.value;
            } else {
                router.push("/");
            }
        }
    };
    const clearUserInfoVo = () => {
        userInfoVo.value = {};
        localStorage.removeItem("UserInfoVo");
    };

    return {
        userInfoVoStr,
        userInfoVo,
        getUserInfoVo,
        setUserInfoVo,
        setUserInfoVoJson,
        clearUserInfoVo,
    };
});